<?php

namespace Summer\Easypay\Http\Controllers;

use Illuminate\Routing\Controller;
use Illuminate\Support\Carbon;
use RainLab\User\Models\User;
use Input;
use Event;
use Auth;
use Db;
use Log;
use Redirect;
use Request;
use Flash;
use RLuders\JWTAuth\Classes\JWTAuth;
use Summer\Activity\Models\ActivitySignModel;
use Summer\Activity\Models\Settings as SignSettings;
use Summer\Easypay\Http\Controllers\Traits\EasyPayFactory;
use Summer\Easypay\Models\EasypayRecordModel;
use Summer\Easypay\Models\EasypaySceneModel;
use Summer\Hjd\Classes\BonusApi;
use Summer\Hjd\Classes\CommonApi;
use Summer\Hjd\Models\CurrencyModel;
use Summer\Hjd\Models\WalletModel;
use Summer\Hub\Http\Controllers\Traits\ApiReturn;
use Summer\Shop\Models\OrderItemModel;
use Summer\Shop\Models\OrderModel;
use Summer\Userhub\Models\OauthModel;
use Winter\Storm\Support\Collection;
use ApplicationException;
use Exception;

class IndexController extends Controller
{
    use ApiReturn;
    use EasyPayFactory;

    /**
     * 调起支付
     * @param JWTAuth $auth
     */
    public function prepay(JWTAuth $auth){
        if (!$user = $auth->user()) {
            return $this->apiError('登录失效,请重新登录');
        }
        //支付场景['goods','recharge']  [商城订单，充值]
        $scene_slug=Input::get('scene_slug');
        if(!$scene_slug){
            return $this->apiError('场景参数错误');
        }
        $scene=EasypaySceneModel::where('slug',$scene_slug)->where('status',1)->first();
        if(!$scene){
            return $this->apiError('场景信息错误');
        }
        //平台类型 ['wxOfficialAccount','wxMiniProgram','H5','App']
        $platform = request()->header('platform');
        if(!in_array($platform,['wxOfficialAccount','wxMiniProgram','H5','App'])){
            return $this->apiError('支付平台类型错误');
        }
        //支付方式 ['wechat','alipay','wallet'] [微信，支付宝，平台货币]
        $payment=Input::get('payment');
        if(!in_array($payment,['wechat','alipay','wallet'])){
            return $this->apiError('请选择正确的支付方式');
        }
        /**
         * 跟据场景判断和处理数据
         *
         * 确定支付的金额  $money
         * 确定支付的SN码  $sn
         * 确定支付的主题  $title
         * 确定支付记录和财务流水对应数据的id  $table_id
         * 确定支付记录和财务流水对应数据的表名  $table_name
         * 确定币种支付时财务流水的流水类型  $change_slug
         *
         */
        if($scene_slug=='goods'){
            $order_sn=Input::get('order_sn');
            if(!$order_sn){
                return $this->apiError('参数错误');
            }
            $order=OrderModel::where('order_sn',$order_sn)->where('user_id',$user->id)->where('status',0)->where('status_slug','nopay')->where('is_pay',0)->first();
            if(!$order){
                return $this->apiError('订单已失效');
            }
            $money=$order->total;
            $sn=$order_sn;
            $title='支付订单';
            $table_id=$order->id;
            $table_name='summer_shop_orders';
            $change_slug='order_pay';
        }
        /**
         * 跟据支付方式判断和处理数据
         */
        //余额支付
        if($payment=='wallet'){
            $currency_slug=Input::get('currency_slug');
            if(!$currency_slug){
                return $this->apiError('请选择支付币种');
            }
            $params['currency_slug']=$currency_slug;
            $params['change_slug']=$change_slug;
            $params['table_id']=$table_id;
            $params['table_name']=$table_name;
        }
        //支付宝支付
        if($payment=='alipay'){
            $params['out_trade_no']=$sn;
            $params['total_amount']=$money;
            $params['subject']=$title;
        }
        //微信支付
        if($payment=='wechat'){
            //微信openid
            $openid=Input::get('openid','');
            //微信公众号和小程序支付需要openid
            if(in_array($platform,['wxOfficialAccount','wxOfficialAccount'])){
                if (isset($openid) && $openid) {
                    $params['openid']=$openid;
                }else{
                    $oauth=OauthModel::where('user_id',$user->id)->where('provider','Wechat')->where('platform',$platform)->first();
                    $params['openid'] = $oauth ? $oauth->openid : '';
                }
                if(empty($params['openid'])){
                    return $this->apiError('缺少openid');
                }
            }
            $params['out_trade_no']=$sn;
            $params['total_fee']=$money*100;
            $params['body']=$title;
        }
        try {
            //删除重复的
            EasypayRecordModel::where('sn',$sn)->where('is_pay',0)->delete();
            //新增支付记录
            $easypay_record=new EasypayRecordModel();
            $easypay_record->sn=$sn;
            $easypay_record->user_id=$user->id;
            $easypay_record->scene=$scene_slug;
            $easypay_record->gateway=$payment;
            $easypay_record->method=$method??'';
            $easypay_record->is_pay=0;
            $easypay_record->params=$params;
            $easypay_record->money=$money;
            $easypay_record->table_id=$table_id;
            $easypay_record->table_name=$table_name;
            $easypay_record->save();
            //支付
            //余额支付
            if($payment=='wallet'){
                $this->walletPay($user,$money,$params);
                $this->walletNotify($sn);
                return $this->apiSuccess('支付成功');
            }
            //支付宝支付
            if($payment=='alipay'){
                $pay_alipay=$this->pay_alipay();
                //跟据平台处理
                if($platform=='App'){
                    $pay_data=$pay_alipay->app($params);
                }else{
                    $pay_data=url('api/easypay/index/alipayPay',['sn'=>$sn]);
                }
                $return['pay_data']=$pay_data;
                return $this->apiSuccess('获取预付款成功',$return);
            }
            //微信支付
            if($payment=='wechat'){
                $pay_wechat=$this->pay_wechat();
                if($platform=='App'){//APP 支付
                    $pay_data= $pay_wechat->app($params);
                }elseif($platform=='H5'){//手机网站支付
                    $pay_data= $pay_wechat->wap($params);
                }elseif($platform=='wxOfficialAccount'){//公众号支付
                    $pay_data= $pay_wechat->mp($params);
                }elseif($platform=='wxMiniProgram'){//小程序支付
                    $pay_data= $pay_wechat->miniapp($params);
                }
                $return['pay_data']=$pay_data;
                return $this->apiSuccess('获取预付款成功',$return);
            }
        }catch (Exception $e){
            return $this->apiError($e->getMessage());
        }
    }

    /**
     * 支付宝支付在除APP环境中调用
     */
    public function alipayPay($sn){
        $easypay_record=EasypayRecordModel::where('sn',$sn)->first();
        if(!$easypay_record || $easypay_record->is_pay!=0 ){
            echo "订单已失效";
            exit;
        }
        $pay_alipay=$this->pay_alipay();
        return $pay_alipay->wap($easypay_record->params);
    }

    /**
     * 余额支付
     */
    public function walletPay($user,$money,$params){
        $currency_slug=$params['currency_slug'];
        $change_slug=$params['change_slug'];
        $table_id=$params['table_id'];
        $table_name=$params['table_name'];
        //余额判断
        $balance=WalletModel::where('currency_slug',$currency_slug)->where('user_id',$user->id)->value('balance');
        if($money>$balance){
            throw new ApplicationException('余额不足');
        }
        //购物扣除
        $commonapi=new CommonApi();
        $commonapi->settleDetailed($user->id,$user->id,$money,0,$currency_slug,[
            'change_slug'=>$change_slug,
            'table_id'=>$table_id,
            'table_name'=>$table_name
        ]);
    }

    /**
     * 余额支付回调
     */
    public function walletNotify($out_trade_no){
        $record=EasypayRecordModel::where('sn',$out_trade_no)->first();
        if(!$record || $record->is_pay!=0 ){
            return false;
        }
        //支付成功操作
        $record->is_pay=1;
        $record->pay_at=Carbon::now();
        $record->save();
        //跟据场景处理
        $this->handleScene($record);
    }
    /**
     * 支付宝支付回调
     * // 请自行对 trade_status 进行判断及其它逻辑进行判断，在支付宝的业务通知中，只有交易通知状态为 TRADE_SUCCESS 或 TRADE_FINISHED 时，支付宝才会认定为买家付款成功。
     * // 1、商户需要验证该通知数据中的out_trade_no是否为商户系统中创建的订单号；
     * // 2、判断total_amount是否确实为该订单的实际金额（即商户订单创建时的金额）；
     * // 3、校验通知中的seller_id（或者seller_email) 是否为out_trade_no这笔单据的对应的操作方（有的时候，一个商户可能有多个seller_id/seller_email）；
     * // 4、验证app_id是否为该商户本身。
     * // 5、其它业务逻辑情况
     */
    public function alipayNotify(){
        $pay_alipay=$this->pay_alipay();
        try{
            $data = $pay_alipay->verify(); // 是的，验签就这么简单！
            Log::info('Alipay notify', $data->all());
            $out_trade_no=$data->out_trade_no;
            $record=EasypayRecordModel::where('sn',$out_trade_no)->first();
            if(!$record || $record->is_pay!=0 ){
                return $pay_alipay->success();// 告诉支付宝，我已经处理完了，订单没找到，别再通知我了
            }
            // 用户是否支付成功
            if ($data->trade_status === 'TRADE_SUCCESS') {
                $record->is_pay=1;
                $record->pay_at=Carbon::now();
                $record->save();
                //跟据场景处理
                $this->handleScene($record);
            } else {// 用户支付失败
                $record->is_pay=-1;
                $record->save();
            }
        } catch (\Exception $e) {
            return $e->getMessage();
        }
        return $pay_alipay->success();
    }
    /**
     * 微信支付回调
     */
    public function wechatNotify(){
        $pay_wechat=$this->pay_wechat();
        try{
            $data = $pay_wechat->verify(); // 是的，验签就这么简单！
            Log::info('Wechat  notify', $data->all());
            $out_trade_no=$data->out_trade_no;
            $record=EasypayRecordModel::where('sn',$out_trade_no)->first();
            if(!$record || $record->is_pay!=0 ){
                return $pay_wechat->success();// 告诉微信，我已经处理完了，订单没找到，别再通知我了
            }
            // 用户是否支付成功
            if ($data->result_code === 'SUCCESS') {
                $record->is_pay=1;
                $record->pay_at=Carbon::now();
                $record->save();
                //跟据场景处理
                $this->handleScene($record);
            } elseif ($data->result_code === 'FAIL') {// 用户支付失败
                $record->is_pay=-1;
                $record->save();
            }
        } catch (\Exception $e) {
            return $e->getMessage();
        }
        return $pay_wechat->success();
    }

    /**
     * 处理场景
     * @param $easypay_record
     */
    public function handleScene($easypay_record){
        if($easypay_record->scene=='goods'){//商城订单支付
            $order=OrderModel::where('id',$easypay_record->table_id)->where('status',0)->where('status_slug','nopay')->where('is_pay',0)->first();
            if($order){
                $order->is_pay=1;
                $order->pay_at=Carbon::now();
                $order->status=1;
                $order->status_slug='nosend';
                $order->save();
                //订单商品状态修改
                OrderItemModel::where('order_id',$order->id)->update(['status_slug'=>'nosend']);
                //支付成功后的订单结算在这里调

            }
        }
    }
    /**
     * 获取支付方式
     */
    public function getPayment(JWTAuth $auth)
    {
        if (!$user = $auth->user()) {
            return $this->apiError('登录失效,请重新登录');
        }
        $scene_slug=Input::get('scene_slug');
        if(!$scene_slug){
            return $this->apiError('场景参数错误');
        }
        $scene=EasypaySceneModel::where('slug',$scene_slug)->where('status',1)->first();
        if(!$scene){
            return $this->apiError('场景信息错误');
        }
        if($scene->methods){
            $currencies=CurrencyModel::whereIn('slug',$scene->methods)->where('status',1)->get();
            $scene->currencies=$currencies;
        }else{
            $scene->currencies=[];
        }
        return $this->apiSuccess('操作成功',$scene);
    }
}
